import axios from 'axios';
import { http } from '@/settings';
import { Message } from 'element-ui';

axios.defaults.headers['Content-Type'] = 'application/json;charset=UTF-8';

// 创建axios实例
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API,
  baseURL: http,
  timeout: 30000,
});
axios.defaults.withCredentials = false; //允许cookie跨域

// 添加请求拦截器，在请求头中加token
service.interceptors.request.use(
  (config) => {
    if (window.sessionStorage.getItem('token') != '') {
      // 需自定义
      // 让每个请求携带token
      config.headers['Authorization'] = window.sessionStorage.getItem('token');
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    //放行000000
    if (response.data.code === '000000') {
      return response.data;
    } else {
      //放行下载
      if (
        response.status === 200 &&
        response.headers['content-type'] ==
          'application/x-msdownload;charset=utf-8'
      ) {
        return response.data;
      }

      //放行导出
      if (
        response.status === 200 &&
        response.headers['content-type'] ==
          'application/vnd.ms-excel;charset=utf-8'
      ) {
        return response.data;
      }

      //放行导出
      if (
        response.status === 200 &&
        response.headers['content-type'] ==
          'application/octet-stream;charset=UTF-8'
      ) {
        return response.data;
      }

      //其他错误
      else {
        Message({
          type: 'error',
          duration: 3000,
          message: response.data.msg,
        });
        return response.data;
      }
    }
  },
  (error) => {
    if (axios.isCancel(error)) {
      if (error.message === '请求已发送，请勿频繁操作') {
        Message({
          type: 'error',
          duration: 3000,
          message: `${error.message}`,
        });
      }
    } else {
      Message({
        type: 'error',
        duration: 3000,
        message: `系统出现未知错误，请联系管理员。错误信息：${error}`,
      });
    }
    return Promise.reject(error);
  }
);

export default service;
